<template>
  <Drawer
    v-model:visible="visible"
    class="custom-class"
    title="监控指标详情"
    :destroyOnClose="true"
    width="100%"
    placement="right"
  >
    <div class="md:flex flex-wrap-reverse">
      <ACol :span="12" class="md:mb-5 md:mx-5">
        <FormItem name="metricType" label="监控指标类型">
          <RadioGroup v-model:value="metricType" button-style="solid">
            <RadioButton value="PAAS.AGGR">集群指标</RadioButton>
            <RadioButton value="PAAS.NODE">主机指标</RadioButton>
            <RadioButton value="PAAS.CONTAINER">容器组件</RadioButton>
          </RadioGroup>
        </FormItem>
      </ACol>
    </div>
    <Card>
      <AForm layout="inline" :model="formState" ref="formRef" v-bind="formItemLayout">
        <ACol :span="6">
          <FormItem
            :rules="{
              required: true,
              message: '请选择监控时间',
            }"
            name="aomTimeRange"
            label="监控时间"
            :labelCol="{ span: 6 }"
          >
            <div class="md:mx-5">
              <RadioGroup v-model:value="formState.aomTimeRange" button-style="solid">
                <RadioButton value="60">近1小时</RadioButton>
                <RadioButton value="180">近3小时</RadioButton>
                <RadioButton value="720">近12小时</RadioButton>
                <RadioButton value="1440">近24小时</RadioButton>
                <!--                  <RadioButton value="10080">近7天</RadioButton>-->
              </RadioGroup>
            </div>
          </FormItem>
        </ACol>
        <ACol :span="3">
          <FormItem
            :rules="{
              required: true,
              message: '请选择监控周期',
            }"
            name="period"
            label="周期"
            :labelCol="{ span: 12 }"
          >
            <div class="md:mx-5">
              <ASelect style="width: 100px" v-model:value="formState.period">
                <SelectOption value="60">1分钟</SelectOption>
                <SelectOption value="300">5分钟</SelectOption>
                <SelectOption value="900">15分钟</SelectOption>
                <SelectOption value="3600">1小时</SelectOption>
              </ASelect>
            </div>
          </FormItem>
        </ACol>
        <ACol :span="4">
          <FormItem
            :rules="{
              required: true,
              message: '请选择聚合方式',
            }"
            name="aomStatistics"
            label="聚合方式"
            :labelCol="{ span: 12 }"
          >
            <div class="md:mx-5">
              <ASelect style="width: 100px" v-model:value="formState.aomStatistics">
                <SelectOption value="maximum">最大值</SelectOption>
                <SelectOption value="minimum">最小值</SelectOption>
                <SelectOption value="sum">求和</SelectOption>
                <SelectOption value="average">平均值</SelectOption>
                <SelectOption value="sampleCount">样本个数</SelectOption>
              </ASelect>
            </div>
          </FormItem>
        </ACol>
        <ACol class="mt-10px" :span="18">
          <FormItem
            :rules="{
              required: true,
              message: '请选择监控指标',
            }"
            name="metrics"
            label="监控指标"
          >
            <div class="md:mx-5">
              <ASelect v-model:value="formState.metrics" mode="multiple" show-search>
                <SelectOption v-for="option in optionList" v-bind:key="option.metricId" :value="option.metricId">
                  {{ option.metricName }}
                </SelectOption>
              </ASelect>
            </div>
          </FormItem>
        </ACol>
        <ACol class="mt-10px" :span="7" v-if="metricType === 'PAAS.CONTAINER'">
          <DynamicContainerForm ref="dynamicFormRef" @getRef="getRef"></DynamicContainerForm>
        </ACol>
        <ACol class="mt-10px ml-28px" :span="7" v-if="metricType === 'PAAS.NODE'">
          <FormItem
            name="nodeIps"
            label="主机"
            :rules="{
              required: true,
              message: '请选择监控主机',
            }"
          >
            <div class="md:mx-5">
              <ASelect v-model:value="formState.nodeIps" mode="multiple" show-search>
                <SelectOption v-for="option in nodeIPsList" v-bind:key="option" :value="option">
                  {{ option }}
                </SelectOption>
              </ASelect>
            </div>
          </FormItem>
        </ACol>
        <div class="absolute top-10px right-10px" :span="7">
          <AButton type="primary" @click="onSubmit">查询</AButton>
          <AButton style="margin-left: 10px" @click="resetForm">重置</AButton>
        </div>
      </AForm>
      <div class="absolute top-20 right-15"></div>
      <div class="md:flex flex-wrap">
        <ChartCard
          class="md:w-3/10 md:h-80 !md:mx-5 !md:my-8"
          v-for="chart in chartList"
          v-bind:key="chart.displayName"
          :displayName="chart.displayName"
          :maxValue="chart.maxValue"
          :minValue="chart.minValue"
          :metricName="chart.metricName"
          :unit="chart.unit"
          :time="chart.time"
          :value="chart.value"
          :preName="chart.preName"
        >
        </ChartCard>
      </div>
    </Card>
    <div class="absolute bottom-10 right-8">
      <AButton style="margin-right: 8px; font-weight: bolder" @click="onClose">取消</AButton>
      <AButton type="primary" style="font-weight: bolder" @click="onClose">确定</AButton>
    </div>
  </Drawer>
</template>

<script lang="ts">
/* eslint-disable*/
import { defineComponent, nextTick, reactive, ref, toRaw, watch } from 'vue';
import {
  Button,
  Col,
  Drawer,
  Form,
  FormItem,
  Select,
  SelectOption,
  Card,
  RadioGroup,
  RadioButton,
} from 'ant-design-vue';
import ChartCard from '/@/views/maintenance-center/resource-monitor/for-platform/components/chartCard.vue';
import {
  getCceMetricList,
  getMonitor,
  getNodeIPList,
} from '/@/api/maintenance-center/resource-monitor/for-platform/resourceMonitor';
import { MonitorParams } from '/@/api/maintenance-center/resource-monitor/for-platform/model/monitorModel';
import DynamicContainerForm from '/@/views/maintenance-center/resource-monitor/for-platform/components/dynamicContainerForm.vue';

export default defineComponent({
  components: {
    DynamicContainerForm,
    ChartCard,
    Card,
    AForm: Form,
    FormItem,
    Drawer,
    AButton: Button,
    ACol: Col,
    ASelect: Select,
    SelectOption,
    RadioGroup,
    RadioButton,
  },
  setup() {
    const visible = ref<boolean>(false);
    const optionList = ref([]);
    const namespace = ref();
    const dimensionValue = ref();
    let dynamicFormRef = ref();
    const formRef = ref();
    let chartList = ref([]);
    const metricType = ref('PAAS.AGGR');
    const nodeIPsList = ref([]);
    const formItemLayout = {
      labelCol: { span: 3 },
      wrapperCol: { span: 24 },
    };
    let formState = reactive<Record<string, any>>({});

    watch(
      () => metricType.value,
      async () => {
        if (metricType.value === 'PAAS.NODE') {
          chartList.value = [];
          formState.aomStatistics = undefined;
          formState.aomTimeRange = undefined;
          formState.period = undefined;
          formState.cesStartTime = undefined;
          formState.cesEndTime = undefined;
          formState.metrics = [];
          nodeIPsList.value = await getNodeIPList({ clusterId: dimensionValue.value });
        } else if (metricType.value === 'PAAS.CONTAINER') {
          chartList.value = [];
          formState.aomStatistics = undefined;
          formState.aomTimeRange = undefined;
          formState.period = undefined;
          formState.cesStartTime = undefined;
          formState.cesEndTime = undefined;
          formState.metrics = [];
        } else if (metricType.value === 'PAAS.AGGR') {
          chartList.value = [];
          formState.aomStatistics = undefined;
          formState.aomTimeRange = undefined;
          formState.cesStartTime = undefined;
          formState.cesEndTime = undefined;
          formState.metrics = [];
          formState.period = undefined;
        }
      }
    );

    async function getCharts(params: MonitorParams) {
      chartList.value = [];
      getMonitor(params).then((res) => {
        res.forEach((item) => {
          item.preName = item.resourceName;
          chartList.value.push(item);
        });
      });
    }

    const getRef = (params: any) => {
      dynamicFormRef.value = params;
    };
    const onSubmit = async () => {
      let params: MonitorParams = {};

      formRef.value.validate().then(async () => {
        params = toRaw(formState);
        params.namespace = namespace.value;
        params.dimensionValue = dimensionValue.value;
        params.cesEndTime = Date.now().toString();
        params.cesStartTime = (params.cesEndTime - params.aomTimeRange * 60 * 1000).toString();
        params.container = [];
        if (metricType.value === 'PAAS.CONTAINER') {
          params.metricNamespace = metricType.value;
          params.clusterId = params.dimensionValue;
          params.container = Object.values(await dynamicFormRef.value.onSubmit());
          params.container.forEach(async (item) => {
            params.nameSpace = item.nameSpace;
            params.appNames = item.appName;
            params.appNames.forEach(async (item) => {
              params.appName = item;
              await getCharts(params);
            });
          });
        } else if (metricType.value === 'PAAS.AGGR') {
          params.metricNamespace = metricType.value;
          params.clusterId = params.dimensionValue;
          getCharts(params);
        } else if (metricType.value === 'PAAS.NODE') {
          params.metricNamespace = metricType.value;
          params.clusterId = params.dimensionValue;
          params.nodeIps?.forEach(async (item) => {
            params.nodeIP = item;
            await getCharts(params);
          });
        }
      });
    };
    const resetForm = () => {
      formRef.value.resetFields();
      formState.metrics = [];
      if (metricType.value === 'PAAS.CONTAINER') {
        console.log(dynamicFormRef.value);
        nextTick(() => {
          dynamicFormRef.value.resetForm();
        });
      }
    };

    const showDrawer = async (params) => {
      visible.value = true;
      namespace.value = params.namespace;
      dimensionValue.value = params.dimensionValue;
      optionList.value = await getCceMetricList({
        metricNamespace: params.namespace,
        clusterId: params.dimensionValue,
      });
    };

    const onClose = async () => {
      chartList.value = null;
      await resetForm();
      formRef.value = null;
      visible.value = false;
    };

    return {
      visible,
      nodeIPsList,
      formState,
      metricType,
      formRef,
      getRef,
      dynamicFormRef,
      formItemLayout,
      onSubmit,
      showDrawer,
      onClose,
      optionList,
      chartList,
      resetForm,
    };
  },
});
</script>
